//
//  SecondViewController.m
//  BeanTrip
//
//  Created by dlios on 15-6-29.
//  Copyright (c) 2015年 PandaGroup. All rights reserved.
//

#import "SecondViewController.h"
#include "UIImageView+WebCache.h"
#import "SecondCollectionViewCell.h"
#import "HTTPTool.h"
#import "HeaderCollectionReusableView.h"

#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
#import "DetailViewController.h"
#import "EuropeViewController.h"
#import "SearchViewController.h"

@interface SecondViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
/**
 *  设置判断section(通过赋值str)
 */
@property (nonatomic, retain) NSString *str;
/**
 *  设置一个小菊花属性
 */
@property (nonatomic, retain) MBProgressHUD *HUD;
/**
 *  设置一个警告效果
 */
@property(nonatomic, retain) UIAlertView *alter;

/**
 *  接受Detailed页面的接口
 */
@property(nonatomic,retain)NSMutableArray *idArr;


@end

@implementation SecondViewController
/**
 *  内存处理
 */
- (void)dealloc
{
    [_MonthArr release];
    [_titleArr release];
    [_trendArr release];
    [_EuropeArr release];
    [_GATArr release];
    [_AmericaArr release];
    [_AsiaArr release];
    [_domesticArr release];
    [_sectionArr release];
    [_alter release];
    [_HUD release];
    [_idArr release];
    [_str release];
    [super dealloc];
}

/**
 *  初始化数组
 *
 *  @param nibNameOrNil   nibNameOrNil description
 *  @param nibBundleOrNil nibBundleOrNil description
 *
 *  @return return value description
 */
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{

    self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
    self.titleArr = [NSMutableArray array];
    self.trendArr = [NSMutableArray array];
    self.EuropeArr = [NSMutableArray array];
    self.GATArr = [NSMutableArray array];
    self.AmericaArr = [NSMutableArray array];
    self.AsiaArr = [NSMutableArray array];
    self.domesticArr = [NSMutableArray array];
    self.sectionArr=[NSArray array];
    self.idArr=[NSMutableArray array];
    }
    return self;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    /**
     *创建搜索框对象,自定义一个控件,继承自UITextField,UITextField *searchBar=[[UITextField alloc] init];
     */

    // 创建首页上面的搜索按钮
    UIButton *mybutton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.view addSubview:mybutton];
    mybutton.frame = CGRectMake(10 * WIDTH/375, 5 * HEIGHT/667, self.view.frame.size.width - 20, 30 * HEIGHT/667);
    [mybutton addTarget:self action:@selector(pushActionn) forControlEvents:(UIControlEventTouchUpInside)];
    mybutton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [mybutton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
   
    // 按钮上的label  用来显示文件
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100 * WIDTH/375, 5 * HEIGHT/667, 200*WIDTH/375, 20 * HEIGHT/667)];
    label.text = @"请输入想搜索的游记";
    label.font = [UIFont systemFontOfSize:17*HEIGHT/667];
    label.textColor = [UIColor lightGrayColor];
    [mybutton addSubview:label];
    // 按钮上的图片
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(80 * WIDTH/375, 5 * HEIGHT/667, 18 * WIDTH/375, 18 * HEIGHT/667)];
    imageV.image = [UIImage imageNamed:@"add_new_poi_search_button"];
  
    [mybutton addSubview:imageV];
    mybutton.layer.cornerRadius = 8;
    mybutton.layer.borderWidth = 1;
    self.navigationItem.titleView = mybutton;
    

    
    /**
    1.创建瀑布流效果

     */
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    /**
     * 2.每一个item的大小
     */
    flowLayout.itemSize=CGSizeMake((WIDTH-30)/2, (HEIGHT-64-49)/4);
    /**
     *  3.设置最小的行间距
     */
     flowLayout.minimumLineSpacing = 10;
    /**
     *  4.设置最小的列间距
     */
    // flowLayout.minimumInteritemSpacing = 0;
    /**
     *  5.滑动的方向(垂直滑动),默认是垂直滑动
     */
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    /**
     *   6.边缘
     */
     flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    /**
    7.创建瀑布流视图
     */
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT-64-49) collectionViewLayout:flowLayout];
    /**
     *8.签订两个协议,一个dataSource,一个delegate
     */
    collectionView.delegate = self;
    collectionView.dataSource = self;
    /**
     *9.把瀑布流视图添加到view上
     */
    [self.view addSubview:collectionView];
    [collectionView release];
    /**
     * 设置瀑布流的背景颜色
     */
    collectionView.backgroundColor=[UIColor whiteColor];
    /**
     * 10.注册
    第一个参数:需要指定注册的类型;第二个参数:重用标志
     */
    [collectionView registerClass:[SecondCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    collectionView.tag=1001;
    /**
     * 给collectionView的头添加一个视图,不能像tableview一样,只能写一个自定义的视图(头视图)
     */
    flowLayout.headerReferenceSize = CGSizeMake(0, 40);
    
    /**
     * 头视图也需要注册
       第二个参数需要指定当前注册是头还是尾,具体的字符串在UICollectionViewFlowLayout类的第十三行和第十四行
     */
    [collectionView registerClass:[HeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];


    /**
     菊花
     
     :returns: return value description
     */
    self.HUD = [[MBProgressHUD alloc] initWithView:collectionView];
    [collectionView addSubview:self.HUD];
    self.HUD.labelText = @"加载中";
    [self.HUD show:YES];
    
    
    /**
     * 11.执行createData方法
     */
    [self createData];

  
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        HeaderCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        view.backgroundColor = [UIColor whiteColor];
      

        
        /**
         *  section里是否带有button,设置默认为NO.
         */
        view.isAdd=NO;
   

        if (indexPath.section==1) {
              view.isAdd=YES;
            [view.myButton addTarget:self action:@selector(click1:) forControlEvents:UIControlEventTouchUpInside];
                }
         else if (indexPath.section==4){
               view.isAdd=YES;
             [view.myButton addTarget:self action:@selector(click2:) forControlEvents:UIControlEventTouchUpInside];
               }
         else if (indexPath.section==5){
               view.isAdd=YES;
                 [view.myButton addTarget:self action:@selector(click3:) forControlEvents:UIControlEventTouchUpInside];
               }
   
        else{
            view.isAdd=NO;
        }
        
     
        
        /**
         *  给myLabel赋值(section里的题目)
         */
    view.myLabel.text = self.titleArr[indexPath.section];
 
      
        
        return view;
    }else{
        return nil;
    }
}

-(void)click1:(UIButton *)button
{
     EuropeViewController *Europe=[[EuropeViewController alloc] init];
     [self.navigationController pushViewController:Europe animated:YES];
     Europe.index=3;
     Europe.titleStr=self.titleArr[1];
     [Europe release];
    }





-(void)click2:(UIButton *)button
{
    EuropeViewController *Asia=[[EuropeViewController alloc] init];
    [self.navigationController pushViewController:Asia animated:YES];
    Asia.index=6;
    Asia.titleStr=self.titleArr[4];
    [Asia release];
}


-(void)click3:(UIButton *)button
{
    EuropeViewController *Domestic=[[EuropeViewController alloc] init];
    [self.navigationController pushViewController: Domestic animated:YES];
    Domestic.index=8;
    Domestic.titleStr=self.titleArr[5];
    [Domestic release];
}

-(void)createData
{

    [HTTPTool get:@"http://api.breadtrip.com/destination/v3/" body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic = result;
    
        /**
         * 12.解析标题数据
         */
        NSArray *elementsArr = dic[@"elements"];
        for (NSDictionary *tempOneDic in elementsArr) {
        [self.titleArr addObject:tempOneDic[@"title"]];
            NSArray *dataArr = tempOneDic[@"data"];
            for (NSDictionary *idDic in dataArr) {
                
            [self.idArr addObject:idDic[@"id"]];
 
            }
            
            
            dataArr = tempOneDic[@"data"];
    //    NSLog(@"%@",self.titleArr);
            /**
             *  把第一个标题去掉
             */
        if ([tempOneDic[@"title"] isEqualToString:@"「本月推荐」玩起来"]) {
    
        [self.titleArr removeObjectAtIndex:0];
        }
            
            /**
             * 13. 热门地点
             */
    if ([tempOneDic[@"title"] isEqualToString:@"热门地点"]) {
        for (NSDictionary *tempTwoDic in dataArr) {
           SecondModel *cover = [[ SecondModel alloc] initWithDic:tempTwoDic];
//            [cover setValuesForKeysWithDictionary:tempTwoDic];
       //      NSLog(@"%@",cover.name);

            [self.trendArr addObject:cover];
    
          }
        }
            
            
            /**
             * 14.欧洲国家
             */
    else if ([tempOneDic[@"title"] isEqualToString:@"欧洲国家"]) {
            for (NSDictionary *tempTwoDic in dataArr) {
           SecondModel *cover = [[ SecondModel alloc] initWithDic:tempTwoDic];

                    [self.EuropeArr addObject:cover];
                }
            }
            /**
             *  15.港澳台
             */
    else if ([tempOneDic[@"title"] isEqualToString:@"港澳台"]) {
                for (NSDictionary *tempTwoDic in dataArr) {
               SecondModel *cover = [[ SecondModel alloc] initWithDic:tempTwoDic];

                    [self.GATArr addObject:cover];
                }
            }
            /**
             *  16.美洲和大洋洲
             */
    else if ([tempOneDic[@"title"] isEqualToString:@"美洲和大洋洲"]) {
          for (NSDictionary *tempTwoDic in dataArr) {
        SecondModel *cover = [[ SecondModel alloc] initWithDic:tempTwoDic];

                    [self.AmericaArr addObject:cover];
                }
            }
            /**
             *  17.亚洲国家
             */
    else if ([tempOneDic[@"title"] isEqualToString:@"亚洲国家"]) {
           for (NSDictionary *tempTwoDic in dataArr) {
            SecondModel *cover = [[ SecondModel alloc] initWithDic:tempTwoDic];

               [self.AsiaArr addObject:cover];
                }
            }
            /**
             *  18.国内城市
             */
    else if ([tempOneDic[@"title"] isEqualToString:@"国内城市"]) {
            for (NSDictionary *tempTwoDic in dataArr) {
           SecondModel *cover = [[ SecondModel alloc] initWithDic:tempTwoDic];

               [self.domesticArr addObject:cover];
                }
            }
        }
        /**
         *  19.通过字面量把数组添加到sectionArr
         */
     self.sectionArr = @[self.trendArr,self.EuropeArr,self.GATArr,self.AmericaArr,self.AsiaArr,self.domesticArr];
        UICollectionView *collectionView = (UICollectionView *)[self.view viewWithTag:1001];
        
        /**
         *  20.重新加载collectionView
         */
       [collectionView reloadData];
        
        
        
        /**
         *加载完成,取消菊花
         */
        [self.HUD removeFromSuperview];
        

     }
     
          failure:^(NSError *error) {
              [self.HUD removeFromSuperview];
        self.alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络请求失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.alter show];
        [self.alter release];
              

              /**
               *  21.如果失败了执行该方法,打印出错误信息
               */

        NSLog(@"%@",error);
    }];
}
 


/**
 *  22.设置section的数目(可选择的方法)
 */
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.titleArr.count;
}

/**
 *  23.collectionView里numberOfItemsInSection(必须要实现的方法
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    //return self.titleArr.count;
    if (section==0) {
        return self.trendArr.count;
    }
    else if (section==1)
    {
        return self.EuropeArr.count;
    }
    else if (section==2)
    {
        return self.GATArr.count;
    }
    else if (section==3)
    {
        return self.AmericaArr.count;
    }
    else if (section==4)
    {
        return self.AsiaArr.count;
    }
    else if (section==5)
    {
        return self.domesticArr.count;
    }
    else
    {return 0;}

}

/**
 *  24.对于每个cell进行操作(必须要实现的方法)
 */
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
  
    SecondCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        /**
         * 创建model对象
         */
     SecondModel *coverPic = self.trendArr[indexPath.row];
        cell.myLabel.text = coverPic.name;
        /**
         * 用sdwebimage对imageview进行图片赋值
         */
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:coverPic.cover]];
        
        
        NSURL *url = [NSURL URLWithString:coverPic.cover];
        UIImage *image = [UIImage imageNamed:@"BeanTrip.png"];
        [cell.myImageView sd_setImageWithURL:url placeholderImage:image];
  
        //动画效果
      

        
        cell.layer.shadowColor = [[UIColor blackColor]CGColor];
        cell.alpha = 0;
        [UIView beginAnimations:@"rotation" context:NULL];
        [UIView setAnimationDuration:1];
        cell.alpha = 1;
        [UIView commitAnimations];
        return cell;
    }
    else if (indexPath.section == 1) {
        SecondModel *coverPic = self.EuropeArr[indexPath.row];
        cell.myLabel.text = coverPic.name;
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:coverPic.cover]];
        
        
        NSURL *url = [NSURL URLWithString:coverPic.cover];
        UIImage *image = [UIImage imageNamed:@"BeanTrip.png"];
        [cell.myImageView sd_setImageWithURL:url placeholderImage:image];
        
        
        
        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            
            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        }];
        return cell;
    }
    else if (indexPath.section == 2) {
       SecondModel *coverPic = self.GATArr[indexPath.row];
        cell.myLabel.text = coverPic.name;
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:coverPic.cover]];
        /**
         *  占位图
         */
        NSURL *url = [NSURL URLWithString:coverPic.cover];
        UIImage *image = [UIImage imageNamed:@"BeanTrip.png"];
        [cell.myImageView sd_setImageWithURL:url placeholderImage:image];
        
        
        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            
            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        }];
        return cell;
    }
    else if (indexPath.section == 3) {
       SecondModel *coverPic = self.AmericaArr[indexPath.row];
        cell.myLabel.text = coverPic.name;
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:coverPic.cover]];
        
        /**
         *  占位图
         */
        NSURL *url = [NSURL URLWithString:coverPic.cover];
        UIImage *image = [UIImage imageNamed:@"BeanTrip.png"];
        [cell.myImageView sd_setImageWithURL:url placeholderImage:image];
        
        
        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            
            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        }];
        return cell;
    }
    else if (indexPath.section == 4) {
       SecondModel *coverPic = self.AsiaArr[indexPath.row];
        cell.myLabel.text = coverPic.name;
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:coverPic.cover]];
        /**
         *  占位图
         */
        NSURL *url = [NSURL URLWithString:coverPic.cover];
        UIImage *image = [UIImage imageNamed:@"BeanTrip.png"];
        [cell.myImageView sd_setImageWithURL:url placeholderImage:image];
        
        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            
            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        }];
        return cell;
    }
    else if (indexPath.section == 5){
        SecondModel *coverPic = self.domesticArr[indexPath.row];
        cell.myLabel.text = coverPic.name;
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:coverPic.cover]];
        /**
         *  占位图
         */
        NSURL *url = [NSURL URLWithString:coverPic.cover];
        UIImage *image = [UIImage imageNamed:@"BeanTrip.png"];
        [cell.myImageView sd_setImageWithURL:url placeholderImage:image];
        
        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            
            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        }];
        return cell;
    }
    else{
        return nil;
    }
    
    
}



/**
 * 点击collection触发方法
 *
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detail = [[DetailViewController alloc] init];
    detail.hidesBottomBarWhenPushed = YES;
    if (indexPath.section==0) {
        SecondModel *secondDetail=self.trendArr[indexPath.row];
        detail.idString=secondDetail.bId;
        detail.typeNumber=secondDetail.type;
        detail.getTitle=self.titleArr[0];
    }
 
    else if (indexPath.section==1) {
        SecondModel *secondDetail=self.EuropeArr[indexPath.row];
        detail.idString=secondDetail.bId;
        detail.typeNumber=secondDetail.type;
         detail.getTitle=self.titleArr[1];
    }
    
    else if (indexPath.section==2) {
        SecondModel *secondDetail=self.GATArr[indexPath.row];
        detail.idString=secondDetail.bId;
        detail.typeNumber=secondDetail.type;
        detail.getTitle=self.titleArr[2];
    }
    
    else if (indexPath.section==3) {
        SecondModel *secondDetail=self.AmericaArr[indexPath.row];
        detail.idString=secondDetail.bId;
        detail.typeNumber=secondDetail.type;
        detail.getTitle=self.titleArr[3];
    }
    
    else if (indexPath.section==4) {
        SecondModel *secondDetail=self.AsiaArr[indexPath.row];
        detail.idString=secondDetail.bId;
        detail.typeNumber=secondDetail.type;
        detail.getTitle=self.titleArr[4];
    }
    
    else if (indexPath.section==5) {
        SecondModel *secondDetail=self.domesticArr[indexPath.row];
        detail.idString=secondDetail.bId;
        detail.typeNumber=secondDetail.type;
        detail.getTitle=self.titleArr[5];
    }
    [self.navigationController pushViewController:detail animated:YES];
    
}



- (void)pushActionn
{
    SearchViewController *sea = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:sea animated:YES];
    [sea release];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    /**
     *键盘回收
     */
    [textField resignFirstResponder];
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
